# coding=UTF-8
from PIL import Image

def plus(str):
    # 返回指定长度的字符串，原字符串右对齐，前面填充0。
    # return str.zfill(8)
    return str.zfill(2)

def getCode(img):
    str = ""
    # 获取到图片的宽和高进行遍历
    for i in range(img.size[0]):
        for j in range(img.size[1]):
            # 获取水印的每个像素值
            rgb = img.getpixel((i, j))
            # 将像素值转为十六进制后保存
            str = str + plus(hex(rgb[0]).replace('0x', ''))
            str = str + plus(hex(rgb[1]).replace('0x', ''))
            str = str + plus(hex(rgb[2]).replace('0x', ''))
    # print(str)
    # print(len(str))
    return str

# img = Image.open('e:\\mms\\载体图片.bmp')
# img = Image.open('e:\\mms\\水印图片.bmp')
# img = Image.open('e:\\mms\\还原加密水印.bmp')
# # img = Image.open('e:\\mms\\还原加密水印.bmp')
# # width = hex(int(str(img.size[0]),10))
# # width = width[2:].zfill(4)
# # print(width)
# # height = hex(int(str(img.size[1]),10))
# # height = height[2:].zfill(4)
# # print(height)
# # 将像素值转为文本
# rgb_img = img.convert('RGB')
# # bincode = getCode(rgb_img)
# # print(len(bincode))
# # print(bincode)
# # hexcode = "{0:0>4X}".format(int(bincode, 2))
# # hexcode = hex(int(bincode, 2))
# hexcode = getCode(rgb_img)
# # print(hexcode)
# print(len(hexcode))
# # hexcode = width + height + hexcode[2:]
# # print(hexcode)
# # print(len(bincode))
# # print(len(hexcode))
# # print(len(bincode)/4)
# # mylist=[]
# # def sep_four(n):#把二进制数按4位分割
# #     for i in range(0,len(n)//128):
# #         a=int(n[4*i:4*i+128],2)
# #         mylist.append("{:x}".format(a))#转成16进制，并添加到列表中

# # filepath = 'e:\\mms\\plaintext.txt'
# filepath = 'e:\\mms\\cryptoout.txt'
# # filepath = 'e:\\mms\\cryptoout.txt'
# # filepath = 'e:\\mms\\cryptoout.txt'
# with open(filepath, 'w') as file_object:
#     # file_object.write(bincode)
#     file_object.write(hexcode)